<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 单位管理(学校管理)
 *
 * @icon fa fa-list
 * @remark
 */
class School extends Backend
{

    /**
     * @var \app\common\model\School
     */
    protected $model = null;
    protected $schoolList = [];
    protected $schoolData = [];
    protected $childrenSchoolIds = [];
    protected $dataLimit = 'auth';
    protected $dataLimitFieldAutoFill = true;

    protected $multiFields = 'ismenu,status';

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('School');

        $this->childrenSchoolIds = $this->auth->getChildrenSchoolIds(true);
        $this->schoolList = collection(\app\common\model\School::where('id', 'in', $this->childrenSchoolIds)->select())->toArray();

        Tree::instance()->init($this->schoolList);
        $result = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $schoolIds = $this->auth->getSchoolIds();
            $schoolList = collection(\app\common\model\School::whereIn('id', $schoolIds)->order('id', 'asc')->select())->toArray();
            Tree::instance()->init($schoolList);
            $row = [];
            foreach ($schoolList as $key => $value) {
                if (!in_array($value['pid'], $schoolIds)) {
                    $row[] = $value['pid'];
                }
            }
            foreach (array_unique($row) as $key => $value) {
                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($value)));
            }

//            $school = \app\common\model\School::get($this->auth->school_id);
//            $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($school->pid)));
        }

        $schoolName = [];
        foreach ($result as $k => $v) {
            $schoolName[$v['id']] = $v['name'];
        }
        $this->schoolData = $schoolName;

        $this->view->assign('schoolData', $this->schoolData);
        $this->assignconfig("admin", ['id' => $this->auth->school_id]);
    }


    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {

            $list = \app\common\model\School::all($this->childrenSchoolIds);
            $list = collection($list)->toArray();

            $schoolList = [];
            foreach ($list as $k => $v) {
                $schoolList[$v['id']] = $v;
            }
            $list = [];
            foreach ($this->schoolData as $k => $v) {
                if (isset($schoolList[$k])) {
                    $schoolList[$k]['name'] = $v;
                    $list[] = $schoolList[$k];
                }
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                try {
                    $code = make_code();
                    while (1) {
                        $count = $this->model->where('code', $code)->count();
                        if (!$count) {
                            break;
                        }
                        $code = make_code();
                    }
                    $params['code'] = $code;

                    $result = $this->model->save($params);

                    $result2 = true;
                    $groups = $this->auth->getGroups();
                    $update_data = [];
                    foreach ($groups as $key => $group) {
                        if ($group['schools'] != '*') {
                            $update_data[] = [
                                'id' => $group['id'],
                                'schools' => $group['schools'] . ',' . $this->model->id
                            ];
                        }
                    }
                    if ($update_data) {
                        $AuthGroup = new AuthGroup;
                        $result2 = $AuthGroup->saveAll($update_data);
                    }

                    if ($result && $result2) {
                        Db::commit();
                        $this->success();
                    } else {
                        $this->error('保存失败');
                    }

                } catch (Exception $e) {

                    $this->error($this->model->getError());
                    Db::rollback();
                }

            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(\app\common\model\School::select())->toArray())->getChildrenIds($row['id']);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child'));
                    }
                }
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $delIds = [];
            foreach (explode(',', $ids) as $k => $v) {
                $delIds = array_merge($delIds, Tree::instance()->getChildrenIds($v, true));
            }

            $delIds = array_unique($delIds);
            $count = $this->model->where('id', 'in', $delIds)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }



}
